package com.itheima.app.manager;

import cn.hutool.Hutool;
import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.crypto.SecureUtil;
import com.alibaba.fastjson.JSON;
import com.itheima.autoconfig.face.AipFaceTemplate;
import com.itheima.autoconfig.huanxin.HuanXinTemplate;
import com.itheima.autoconfig.oss.OssTemplate;
import com.itheima.autoconfig.sms.SmsTemplate;
import com.itheima.domain.db.Log;
import com.itheima.domain.db.User;
import com.itheima.domain.db.UserInfo;
import com.itheima.service.db.UserInfoService;
import com.itheima.service.db.UserService;
import com.itheima.util.ConstantUtil;
import com.itheima.util.JwtUtil;
import com.itheima.vo.ErrorResult;
import com.itheima.vo.UserInfoVo;
import org.apache.dubbo.config.annotation.Reference;
import org.apache.rocketmq.spring.core.RocketMQTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.time.Duration;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@Component
public class UserManager {

    @Reference // dubbo的
    private UserService userService;

    @Autowired
    private SmsTemplate smsTemplate;

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Reference
    private UserInfoService userInfoService;

    @Autowired
    private AipFaceTemplate aipFaceTemplate;

    @Autowired
    private OssTemplate ossTemplate;

    @Autowired
    private HuanXinTemplate huanXinTemplate;

    @Autowired
    private RocketMQTemplate rocketMQTemplate;

    // 接收保存请求
    public ResponseEntity save(User user) {
        // 密码MD5加密
        user.setPassword(SecureUtil.md5(user.getPassword()));
        Long userId = userService.save(user);
        return ResponseEntity.ok(userId);
    }

    // 接收根据手机号查询请求
    public ResponseEntity findByPhone(String phone) {
        User user = userService.findByPhone(phone);
        return ResponseEntity.ok(user);
    }

    // 发送短信验证码
    public void sendSms(String phone) {
        // 1.生成6位验证码
        String code = "123456";
        // 2.发送短信  // TODO  产品上线前需要开启短信发送
        // smsTemplate.sendSms(phone, code);

        // 3.将验证码存入redis中
        stringRedisTemplate.opsForValue().set(ConstantUtil.SMS_CODE + phone, code, Duration.ofMinutes(5));
    }

    // 注册登录
    public ResponseEntity regAndLogin(String phone, String verificationCode) {
        // 1.对比验证码
        // 1-1 获取redis中验证码
        String codeFromRedis = stringRedisTemplate.opsForValue().get(ConstantUtil.SMS_CODE + phone);
        // 1-2 完成对比
        if (!StrUtil.equals(verificationCode, codeFromRedis)) {
            // 失败
            return ResponseEntity.status(500).body(ErrorResult.loginError());
        }
        // 1-3 清除redis验证码
        stringRedisTemplate.delete(ConstantUtil.SMS_CODE + phone);
        // 2.手机号查询用户
        User user = userService.findByPhone(phone);
        boolean isNew;

        String type="0101";

        if (user == null) { // 2-1 新用户，完成注册
            isNew = true;
            user = new User();
            user.setPhone(phone);
            user.setPassword(SecureUtil.md5(user.getPassword()));
            // 调用rpc保存
            Long userId = userService.save(user);
            user.setId(userId);

            type = "0102";
            // 向环信注册此用户
            huanXinTemplate.register(userId);

        } else { // 2-2 老用户
            isNew = false;
        }

        // 发送mq消息
        Log log = new Log();
        log.setUserId(user.getId()); // 操作人
        log.setLogTime(DateUtil.formatDate(new Date())); // 操作时间
        log.setPlace("北京顺义马坡");
        log.setEquipment("小米11");
        log.setType(type);

        rocketMQTemplate.convertAndSend("tanhua-log", log);

        // 3.制作token
        user.setPassword(null);
        Map<String, Object> claims = BeanUtil.beanToMap(user);
        String token = JwtUtil.createToken(claims);

        // 3-1 redis指定token存活时间（1天）
        String json = JSON.toJSONString(user);
        stringRedisTemplate.opsForValue().set(ConstantUtil.USER_TOKEN + token, json, Duration.ofDays(5));

        // 4.返回结果
        Map<String, Object> resultMap = new HashMap<>();
        resultMap.put("token", token);
        resultMap.put("isNew", isNew);
        return ResponseEntity.ok(resultMap);
    }

    // 完善用户信息
    public void saveUserInfoBase(UserInfo userInfo, String token) {
        // 1.解析token，返回user，续期token
        User user = findUserByToken(token);
        // 2.给userInfo指定用户id
        userInfo.setId(user.getId());
        // 3.完成rpc保存
        userInfoService.save(userInfo);
    }

    // 根据token获得user对象
    public User findUserByToken(String token) {
        // 1. 从redis中获得token
        String json = stringRedisTemplate.opsForValue().get(ConstantUtil.USER_TOKEN + token);
        // 2.非空处理
        if (StrUtil.isEmpty(json)) {
            return null;
        }
        // 3.转换为user对象
        User user = JSON.parseObject(json, User.class);

        // 4.完成续期操作
        stringRedisTemplate.opsForValue().set(ConstantUtil.USER_TOKEN + token, json, Duration.ofDays(5));
        return user;
    }

    public ResponseEntity saveUserInfoPhoto(MultipartFile headPhoto, String token) throws IOException {
        // 0.解析token
        User user = findUserByToken(token);
        // 1.人脸检测
        boolean detect = aipFaceTemplate.detect(headPhoto.getBytes());
        if (!detect) {
            // 非人脸
            return ResponseEntity.status(500).body(ErrorResult.faceError());
        }
        // 2.oss上传
        String urlPath = ossTemplate.upload(headPhoto.getOriginalFilename(), headPhoto.getInputStream());

        // 3.创建userInfo
        UserInfo userInfo = new UserInfo();
        userInfo.setId(user.getId());
        userInfo.setAvatar(urlPath); // 头像
        userInfo.setCoverPic(urlPath); // 封面

        // 4.调用rpc更新
        userInfoService.update(userInfo);

        return ResponseEntity.ok(null);
    }

    // 查询用户信息
    public ResponseEntity findUserInfoVo(Long userId) {
        // 1.调用rpc查询
        UserInfo userInfo = userInfoService.findByUserId(userId);

        // 2.构建vo
        UserInfoVo userInfoVo = new UserInfoVo();
        BeanUtil.copyProperties(userInfo, userInfoVo);

        // 2-1 处理age特殊字段
        if (userInfo.getAge() != null) {
            userInfoVo.setAge(userInfo.getAge().toString());
        }

        // 3.返回vo
        return ResponseEntity.ok(userInfoVo);
    }

    // 更新用户基本信息
    public void updateUserInfoBase(UserInfo userInfo, String token) {
        // 1.解析token
        User user = findUserByToken(token);
        // 2.调用rpc实现更新
        userInfo.setId(user.getId());
        userInfoService.update(userInfo);
    }
}
